package org.example;/*
 * title:
 * author:
 * date:
 * description:
 * */

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/max")
public class MaxDate {
    @Resource
    private ThreadPoolTaskExecutor taskExecutor1;

    
    /*@Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;*/
    /*private ThreadPoolTaskExecutor executor;

    @Autowired
    public void setThreadPoolTaskExecutor(ThreadPoolTaskExecutor executor) {
        this.executor = executor;
    }*/

    @GetMapping("/maxDate")
    public   String maxDate() {

        long start = System.currentTimeMillis();

        List<LocalDate> latestDate = new ArrayList<>();
        CompletableFuture<Void> docFuture = CompletableFuture.runAsync(() -> {
            String idAbsPath = "24030814|21782164|21782201|22318528|22039835";
            String lang = "zh";
            String tid = "22039835";
            String offeringName = "AP5000";
            LocalDate latestDateDoc = maxDateDoc(idAbsPath, lang, tid, offeringName);
            System.out.println("最晚的doc日期是：" + latestDateDoc);
            latestDate.add(latestDateDoc);
        },  taskExecutor1);

        CompletableFuture<Void> caseFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsCase = "https://support.huawei.com/enterpriseproduct/AggregationPageTabController/getKnowledgeInfoListByPbiIds?pageIndex=0&orderBy=publishTime+desc&scene=-1&level=-1&resourceType=0&subModelOfferingId=&pageType=0&itemsPerPage=20&pbiIds=22039835&level1=24030814&requestType=ajax.json";
            LocalDate latestDateCase = maxDateCase(baseUrlParamsCase);
            System.out.println("最晚的case日期是：" + latestDateCase);
            latestDate.add(latestDateCase);
        },  taskExecutor1);

        CompletableFuture<Void> softFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsSoft = "https://support.huawei.com/enterpriseproduct/AggregationPageController/selectVersionList?idAbsPath=fixnode01%7C24030814%7C21782164%7C21782201%7C22318528%7C22039835&subModelOfferingId=&requestType=ajax.json";
            LocalDate latestDateSoft = maxDateSoft(baseUrlParamsSoft);
            System.out.println("最晚的soft日期是：" + latestDateSoft);
            latestDate.add(latestDateSoft);
        },  taskExecutor1);

        CompletableFuture<Void> newsFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsNews = "https://support.huawei.com/enterpriseproduct/AggregationPageTabController/getNewsTotalRow?idAbsPath=22039835&newsType=&subModelOfferingId=&pageIndex=0&pageSize=20&requestType=ajax.json";
            LocalDate latestDateNews = maxDateNews(baseUrlParamsNews);
            System.out.println("最晚的news日期是：" + latestDateNews);
            latestDate.add(latestDateNews);
        },  taskExecutor1);

        CompletableFuture<Void> toolsFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsTools = "https://support.huawei.com/enterpriseproduct/AggregationPageController/getOfferingToolInfoList?idAbsPath=24030814%7C21782164%7C21782201%7C22318528%7C22039835&subModelOfferingId=";
            LocalDate latestDateTools = maxDateTools(baseUrlParamsTools);
            System.out.println("最晚的tools日期是：" + latestDateTools);
            latestDate.add(latestDateTools);
        },  taskExecutor1);

        CompletableFuture<Void> videosFuture = CompletableFuture.runAsync(() -> {
            String baseUrlParamsVideos = "https://support.huawei.com/enterpriseproduct/AggregationPageTabController/getVideoByCondition?pbiList=22039835&scene=&year=&mediatype=&fromSize=0&pageSize=20&orderBy=&isAsc=&orderBy2=&isAsc2=&requestType=ajax.json&scenario=&subModelOfferingId=&date_name=&mediatype_name=&scen_all=&scenType=new";
            LocalDate latestDateVideos = maxDateVideos(baseUrlParamsVideos);
            System.out.println("最晚的videos日期是：" + latestDateVideos);
            latestDate.add(latestDateVideos);
        },  taskExecutor1);
        CompletableFuture.allOf(docFuture, caseFuture, softFuture, newsFuture, toolsFuture, videosFuture).join();

        LocalDate maxPublishDate = latestDate.stream()
                .max(Comparator.naturalOrder())
                .orElseThrow(() -> new IllegalStateException("集合为空，无法找到最晚日期"));
        System.out.println("maxPublishDate日期是：" + maxPublishDate);
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));
        return maxPublishDate.toString();
    }

    private   LocalDate maxDateSoft(String baseUrlParams) {
        try {
            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串


                List<String> publishTimes = extractPublishTimesSoft(jsonStr);
                System.out.println(publishTimes);

                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                List<LocalDate> dates = new ArrayList<>();
                for (String dateTimeStr : publishTimes) {
                    LocalDate date = LocalDate.parse(dateTimeStr, dateFormatter);
                    dates.add(date);
                }

                // 使用流和Comparator找出最晚的日期
                LocalDate latestDate = dates.stream()
                        .max(Comparator.naturalOrder())
                        .orElseThrow(() -> new IllegalStateException("集合为空，无法找到最晚日期"));

                return latestDate;

            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private   List<String> extractPublishTimesSoft(String jsonStr) {
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> publishTimes = new ArrayList<>();
        try {
            JsonNode rootNode = objectMapper.readTree(jsonStr);

            // 获取vrList属性的值
            String vrListValue = rootNode.get("vrList").asText();

            Pattern pattern = Pattern.compile("\\b\\d{4}-\\d{2}-\\d{2}\\b"); // 匹配 yyyy-MM-dd 格式的日期
            Matcher matcher = pattern.matcher(vrListValue);

            while (matcher.find()) {
                publishTimes.add(matcher.group());
            }

        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("解析JSON时发生错误");
        }
        return publishTimes;
    }

    public   LocalDate maxDateDoc(String idAbsPath, String lang, String tid, String offeringName) {
        try {
            // 对包含空格的参数进行URL编码
            offeringName = URLEncoder.encode(offeringName, StandardCharsets.UTF_8.toString()).replace("+", "%20");

            // 拼接URL
            StringBuilder baseUrlParams = new StringBuilder();
            baseUrlParams.append("https://support.huawei.com/enterpriseproduct/AggregationPageController/getDocTypeAllX?")
                    .append("idAbsPath=").append(idAbsPath)
                    .append("&lang=").append(lang)
                    .append("&tid=").append(tid)
                    // 注意：belongVersionId, vrId, subModelOfferingId, orderBy, isAsc, businessScenario, requestType 参数值为空，直接附加
                    .append("&belongVersionId=")
                    .append("&vrId=")
                    .append("&subModelOfferingId=")
                    .append("&orderBy=")
                    .append("&isAsc=")
                    .append("&offeringName=").append(offeringName)
                    .append("&businessScenario=")
                    .append("&requestType=ajax.json");

            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串
                List<String> publishTimes = extractPublishTimes(jsonStr);
                System.out.println(publishTimes);
                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                List<LocalDate> dates = new ArrayList<>();
                for (String dateTimeStr : publishTimes) {
                    LocalDate date = LocalDate.parse(dateTimeStr.split(" ")[0], dateFormatter);
                    dates.add(date);
                }

                // 使用流和Comparator找出最晚的日期
                LocalDate latestDate = dates.stream()
                        .max(Comparator.naturalOrder())
                        .orElseThrow(() -> new IllegalStateException("集合为空，无法找到最晚日期"));

                return latestDate;
            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private   List<String> extractPublishTimes(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        List<String> publishTimes = new ArrayList<>();

        try {
            JsonNode rootNode = mapper.readTree(jsonStr);

            // 遍历根节点下的所有元素
            Iterator<JsonNode> elements = rootNode.elements();
            while (elements.hasNext()) {
                JsonNode element = elements.next();

                // 获取并遍历每个"subAggs"
                JsonNode subAggsNode = element.get("subAggs");
                if (subAggsNode != null && subAggsNode.isArray()) {
                    Iterator<JsonNode> subAggElements = subAggsNode.elements();
                    while (subAggElements.hasNext()) {
                        JsonNode subAggElement = subAggElements.next();

                        // 获取并遍历每个"docList"
                        JsonNode docListNode = subAggElement.get("docList");
                        if (docListNode != null && docListNode.isArray()) {
                            Iterator<JsonNode> docListElements = docListNode.elements();
                            while (docListElements.hasNext()) {
                                JsonNode docElement = docListElements.next();
                                // 提取publishTime
                                String publishTime = docElement.get("publishTime").asText();
                                publishTimes.add(publishTime);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return publishTimes;
    }

    public   LocalDate maxDateCase(String baseUrlParams) {
        try {
            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串


                List<String> publishTimes = extractPublishTimesEasy(jsonStr);
                System.out.println(publishTimes);

                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                List<LocalDate> dates = new ArrayList<>();
                for (String dateTimeStr : publishTimes) {
                    LocalDate date = LocalDate.parse(dateTimeStr, dateFormatter);
                    dates.add(date);
                }

                // 使用流和Comparator找出最晚的日期
                LocalDate latestDate = dates.stream()
                        .max(Comparator.naturalOrder())
                        .orElseThrow(() -> new IllegalStateException("集合为空，无法找到最晚日期"));

                return latestDate;

            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private   List<String> extractPublishTimesEasy(String jsonStr) {
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> publishTimes = new ArrayList<>();
        try {
            JsonNode rootNode = objectMapper.readTree(jsonStr);

            // 确保JSON是一个数组
            if (rootNode.isArray()) {

                for (JsonNode node : rootNode) {
                    // 直接提取publishTime属性的值
                    String publishTime = node.get("publishTime").asText();
                    publishTimes.add(publishTime);
                }
            } else {
                System.out.println("JSON数据不是数组");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return publishTimes;
    }

    public   LocalDate maxDateNews(String baseUrlParams) {
        try {
            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串


                String publishTime = extractPublishTimesNews(jsonStr);
                System.out.println(publishTime);

                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                LocalDate latestDate = LocalDate.parse(publishTime.split(" ")[0], dateFormatter);

                return latestDate;

            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private   String extractPublishTimesNews(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        String firstPublishTime = null;
        try {
            // 将JSON字符串直接解析为JsonNode数组
            JsonNode rootNode = mapper.readTree(jsonStr).path("totalRow");

            if (rootNode.isArray() && rootNode.size() > 0) {
                // 获取第一个元素的publishTime属性
                firstPublishTime = rootNode.get(0).get("publishTime").asText();
            } else {
                System.out.println("JSON数据不包含totalRow或totalRow为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("解析JSON时发生错误");
        }
        return firstPublishTime;
    }

    public   LocalDate maxDateTools(String baseUrlParams) {
        try {
            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串


                List<String> publishTimes = extractPublishTimesTools(jsonStr);
                System.out.println(publishTimes);

                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 提取每个字符串的日期部分并转换为LocalDate对象
                List<LocalDate> dates = new ArrayList<>();
                for (String dateTimeStr : publishTimes) {
                    LocalDate date = LocalDate.parse(dateTimeStr.split(" ")[0], dateFormatter);
                    dates.add(date);
                }

                // 使用流和Comparator找出最晚的日期
                LocalDate latestDate = dates.stream()
                        .max(Comparator.naturalOrder())
                        .orElseThrow(() -> new IllegalStateException("集合为空，无法找到最晚日期"));

                return latestDate;

            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private   List<String> extractPublishTimesTools(String jsonStr) {
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> publishTimes = new ArrayList<>();
        try {
            JsonNode rootNode = objectMapper.readTree(jsonStr);

            // 确保JSON是一个数组
            if (rootNode.isArray()) {

                for (JsonNode node : rootNode) {
                    // 直接提取publishTime属性的值
                    String lastUpdateTime = node.get("lastUpdateTime").asText();
                    publishTimes.add(lastUpdateTime);
                }
            } else {
                System.out.println("JSON数据不是数组");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return publishTimes;
    }

    public   LocalDate maxDateVideos(String baseUrlParams) {
        try {
            URL url = new URL(baseUrlParams.toString());

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 设置可以输出
            connection.setFixedLengthStreamingMode(0);
            // 设置请求属性
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            // 写入POST请求的数据（这里假设参数已经在URL中，通常POST请求会在下面这行写入参数，但按需调整）
            //OutputStream os = connection.getOutputStream();
            //os.write(params.getBytes(StandardCharsets.UTF_8));
            //os.flush();
            //os.close();

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { // 200或201表示成功
                // 读取响应内容
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder content = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }

                in.close();
                connection.disconnect(); // 关闭连接

                String jsonStr = content.toString(); // 这里放置整个JSON字符串
                String publishTime = extractPublishTimesVideos(jsonStr);
                System.out.println("第一个视频的publishTime为: " + publishTime);
                // 定义日期格式器，仅用于日期部分
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                LocalDate latestDate = LocalDate.parse(publishTime.split(" ")[0], dateFormatter);

                return latestDate;
            } else {
                System.out.println("HTTP POST 请求失败，响应码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private   String extractPublishTimesVideos(String jsonStr) {
        ObjectMapper mapper = new ObjectMapper();
        String firstPublishTime = null;
        try {
            JsonNode rootNode = mapper.readTree(jsonStr).get("videoList");

            if (rootNode.isArray() && rootNode.size() > 0) {
                firstPublishTime = rootNode.get(0).get("publishTime").asText();
            } else {
                System.out.println("videoList为空或不是数组");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("解析JSON时发生错误");
        }
        return firstPublishTime;
    }
}
